package com.yzt.loginmodule.login;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.arouter.RouterAccount;
import com.yzt.zhuju.arouter.RouterMain;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.config.AppConfigCacheManager;
import com.yzt.zhuju.event.main.LoginCloseEvent;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.login.LoginOrRegisterRequest;
import com.yzt.zhuju.network.entity.user.UserLoginInfo;
import com.yzt.zhuju.utils.AppDialogUtil;
import com.yzt.loginmodule.R;
import com.yzt.p_base.utils.KeyboardUtils;
import com.yzt.p_base.utils.MD5Util;
import com.yzt.plugin_network.excep.HttpStatus;

/**
 * author : bob
 * date   : 2022/12/1
 * desc   : 密码登录
 */
@SuppressLint("SetTextI18n")
@Route(path = RouterAccount.ACTIVITY_PASSWORD_LOGIN)
public class PasswordLoginActivity extends BaseActivity {

    @Autowired
    String mobile;

    @Autowired
    boolean isAgree;

    @Autowired
    String zone;
    /**
     * 1:登录/注册；2：重置密码；
     */
    @Autowired
    int type;

    private ImageView ivOpenOrClose;
    private EditText etInputMobileNo;
    private EditText etPwd;
    private TextView tvSure;
    private TextView tvCountryCode;

    @Override
    public int getLayoutId() {
        return R.layout.activity_password_login;
    }

    @Override
    public void installViews() {
        setFullScreen(true, R.color.transparent);
        etPwd = findViewById(R.id.et_passwd);
        etInputMobileNo = findViewById(R.id.et_input_mobile_no);
        tvSure = findViewById(R.id.tv_sure);
        ivOpenOrClose = findViewById(R.id.iv_open_or_close);
        tvCountryCode = findViewById(R.id.tv_country_code);
        if (!TextUtils.isEmpty(mobile)) {
            etInputMobileNo.setText(mobile);
        }
        if (!TextUtils.isEmpty(zone)) {
            tvCountryCode.setText("+" + zone);
        } else {
            tvCountryCode.setText("+" + RXingUtils.getDefaultZonde());
        }

        findViewById(R.id.tv_sms_login).setOnClickListener(this);
        findViewById(R.id.tv_forget_passwd).setOnClickListener(this);
        findViewById(R.id.iv_title_left).setOnClickListener(this);
        tvSure.setOnClickListener(this);
        ivOpenOrClose.setOnClickListener(this);
        tvCountryCode.setOnClickListener(this);
        ivOpenOrClose.setSelected(false);
        setTextWatcher();
        setCommitStatus();
        observerRxBus(LoginCloseEvent.class, event -> finish());
    }

    @Override
    protected void onClick(int clickId) {
        super.onClick(clickId);
        if (clickId == R.id.tv_sms_login) {
            //判断大于6位，就传递手机号
            String mobile = etInputMobileNo.getText().toString();
            String code = tvCountryCode.getText().toString().replace("+", "");
            if (mobile.length() < 6) {
                mobile = "";
            }
            RouterAccount.SMSLoginActivity(mActivity, mobile, code, type, true);
            finish();
        } else if (clickId == R.id.tv_forget_passwd) {
            RouterAccount.FindPasswordActivity(mActivity, 2);
        } else if (clickId == R.id.tv_help) {
            RouterMain.goToWeb(String.format(getString(R.string.login_user_help)));
        } else if (clickId == R.id.iv_title_left) {
            mActivity.finish();
        } else if (clickId == R.id.tv_country_code) {
            //RouterAccount.RegisterSelectZone(mActivity);
        } else if (clickId == R.id.tv_sure) {
            KeyboardUtils.hideSoftInput(this);
            onLoginClick();
        } else if (clickId == R.id.iv_open_or_close) {
            onShowOrCloseClick();
        }
    }

    private void onShowOrCloseClick() {
        ivOpenOrClose.setSelected(!ivOpenOrClose.isSelected());
        if (ivOpenOrClose.isSelected()) {
            ivOpenOrClose.setImageResource(R.mipmap.login_password_open);
        } else {
            ivOpenOrClose.setImageResource(R.mipmap.login_password_close);
        }
        etPwd.setTransformationMethod(ivOpenOrClose.isSelected() ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
        etPwd.setSelection(etPwd.getText().length());
    }

    private void setTextWatcher() {
        etInputMobileNo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setCommitStatus();
            }
        });
        etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setCommitStatus();
            }
        });
    }

    private void setCommitStatus() {
        String mobile = etInputMobileNo.getText().toString();
        String passWord = etPwd.getText().toString();
        tvSure.setEnabled(mobile.length() >= 6 && passWord.length() >= 6);
    }

    private void onLoginClick() {

        tvSure.setEnabled(false);

        String mobile = etInputMobileNo.getText().toString();
        String passWord = etPwd.getText().toString();
        int nationCode = Integer.parseInt(tvCountryCode.getText().toString().replace("+", ""));

        LoginOrRegisterRequest mLoginOrRegisterRequest = new LoginOrRegisterRequest();
        mLoginOrRegisterRequest.setMobile(mobile);
        mLoginOrRegisterRequest.setPassWord(MD5Util.md5(passWord));
        mLoginOrRegisterRequest.setNationCode(nationCode);
        showMProgress();
        login(mLoginOrRegisterRequest);
    }

    private void login(LoginOrRegisterRequest mLoginOrRegisterRequest) {
        mLoginOrRegisterRequest.setShumeiDeviceId(AppConfigCacheManager.getInstance().getDeviceId());
        BizLayer.getInstance().getAccountModule().postLogin(mLoginOrRegisterRequest, new LoginSubscriber());
    }

    private class LoginSubscriber extends AresSubscriber<UserLoginInfo> {

        @Override
        protected void onSuccess(UserLoginInfo mUserLoginInfo) {
            mUserLoginInfo.getUserInfo().setPhoneLogin(true);
            BizLayer.getInstance().getAccountModule().getIMToken(new AresSubscriber<UserLoginInfo>() {
                @Override
                protected void onSuccess(UserLoginInfo data) {
                    mUserLoginInfo.getUserInfo().setRongappid(data.getToken());
                    RXingUtils.saveLoginAccount(mUserLoginInfo);
                    RouterMain.MainActivity();
                    mActivity.setResult(RESULT_OK);
                    mActivity.finish();
                }
            });
        }

        @Override
        protected void onError(int code, String info) {
            super.onError(code, info);
            onErrorCode(code);
        }

        @Override
        protected void onFinallyEnd() {
            super.onFinallyEnd();
            closeProgress();
            tvSure.setEnabled(true);
        }
    }

    private void onErrorCode(int code) {
        if (code == HttpStatus.ResponseStatus.NOT_REGISTER) {
            AppDialogUtil.showTitleDialog(mActivity, R.string.hint, R.string.account_not_register, R.string.cancel, R.string.register_now, new AppDialogUtil.DialogClickInterface() {
                @Override
                public void onCancelClick() {

                }

                @Override
                public void onSureClick() {
                    RouterAccount.SMSLoginActivity(mActivity, etInputMobileNo.getText().toString(),
                            tvCountryCode.getText().toString().replace("+", ""), 1, true);
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        if (requestCode == RouterAccount.AccountRequestCode.REQUEST_SELECT_ZONE) {
            setCountryCode(data.getStringExtra("countryNumber"));
        } else if (requestCode == RouterAccount.AccountRequestCode.REQUEST_CODE_LOGIN) {
            mActivity.setResult(RESULT_OK);
            mActivity.finish();
        } else if (requestCode == RouterAccount.AccountRequestCode.REQUEST_FORGET_PASSWD_CODE) {

        } else {
            mActivity.setResult(RESULT_OK);
            mActivity.finish();
        }
    }

    private void setCountryCode(String countryNumber) {

        tvCountryCode.setText(countryNumber);
    }
}

